<template>
  <div>
    <form class="card comment-form" @submit.prevent="handlePost">
      <div class="card-block">
        <textarea
          v-model="textarea"
          class="form-control"
          placeholder="Write a comment..."
          rows="3"
        ></textarea>
      </div>
      <div class="card-footer">
        <img :src="user.image" class="comment-author-img" />
        <button class="btn btn-sm btn-primary" :disabled="postLoading">
          Post Comment
        </button>
      </div>
    </form>

    <div v-for="c in comments" :key="c.id" class="card">
      <div class="card-block">
        <p class="card-text">
          {{ c.body }}
        </p>
      </div>
      <div class="card-footer">
        <a href="" class="comment-author">
          <img :src="c.author.image" class="comment-author-img" />
        </a>
        &nbsp;
        <nuxt-link :to="`/profile/${c.author.username}`" class="comment-author">
          {{ c.author.username }}
        </nuxt-link>
        <span class="date-posted">{{ c.createdAt | date }}</span>
        <span
          v-if="c.author.username === user.username"
          class="mod-options"
          @click="handleDelete(c)"
        >
          <i class="ion-trash-a"></i>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getComments, addComments, deleteComments } from '@/api/article'

export default {
  name: 'ArticleComment',
  props: {
    slug: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      comments: [],
      postLoading: false,
      textarea: '',
    }
  },
  computed: {
    ...mapState(['user']),
  },
  mounted() {
    this.loadComments()
  },
  methods: {
    loadComments() {
      getComments(this.slug).then(({ comments }) => {
        this.comments = comments
      })
    },
    handlePost() {
      this.postLoading = true
      addComments(this.slug, this.textarea)
        .then(() => {
          this.textarea = ''
          this.loadComments()
        })
        .finally(() => {
          this.postLoading = false
        })
    },
    handleDelete(item) {
      if (item.deleteDisabled) return
      item.deleteDisabled = true
      deleteComments(this.slug, item.id).then(() => {
        this.textarea = ''
        this.loadComments()
      })
    },
  },
}
</script>

<style scoped></style>
